package com.example.draganddraw;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.PointF;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import androidx.annotation.Nullable;
import java.util.ArrayList;
import java.util.List;

public class BoxDrawingView extends View {
    private static final  String TAG = "BoxDrawingView";//log标记
    private Box mCurrentBox;//单一触摸点对象
    private List<Box> mBoxen = new ArrayList<>();//存储触摸点的容器
    private Paint mBoxPaint;
    private Paint mBackgroundPaint;
    public BoxDrawingView(Context context) {
        super(context);
    }

    public BoxDrawingView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        mBoxPaint = new Paint();
        mBoxPaint.setColor(0x22ff0000);
        mBackgroundPaint = new Paint();
        mBackgroundPaint.setColor(0xfff8efe0);
    }

    public BoxDrawingView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        PointF current = new PointF(event.getX(),event.getY());
        String action = "";
        switch (event.getAction()){
            case MotionEvent.ACTION_DOWN://手指按下去的动作
                action = "ACTION_DOWN";
                mCurrentBox = new Box(current);
                mBoxen.add(mCurrentBox);//每次按下去都会新生成对象添加进容器
                break;
            case MotionEvent.ACTION_MOVE:
                action = "ACTION_MOVE";
                if (mCurrentBox!=null){
                    mCurrentBox.setmCurrent(current); //手指移动的时候给容器设置数据
                    invalidate();//强制BoxDrawingView来绘制自己
                }
                break;
            case MotionEvent.ACTION_UP:
                action ="ACTION_UP";
                mCurrentBox = null;
                break;
            case MotionEvent.ACTION_CANCEL:
                action ="ACTION_CANCEL";
                mCurrentBox = null;
                break;
        }
//        Log.i(TAG, action+"at x="+current.x+",y="+current.y);
        return true;
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        for (Box box : mBoxen){
            float left  = Math.min(box.getmOrigin().x,box.getmCurrent().x);
            Log.i(TAG, "onDraw: left"+left);
            float right = Math.max(box.getmOrigin().x,box.getmCurrent().x);
            Log.i(TAG, "onDraw: right"+right);
            float top = Math.min(box.getmOrigin().y,box.getmCurrent().y);
            Log.i(TAG, "onDraw:top "+top);
            float bottom = Math.max(box.getmOrigin().y,box.getmCurrent().y);
            Log.i(TAG, "onDraw: bottom"+bottom);
            canvas.drawRect(left,top,right,bottom,mBoxPaint);
        }
    }
}
